package com.firefly.mq.redisMq.jobhandle;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;


/**
 * @description: 接收订阅到的任务，并转发到任务处理
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/10/28
 **/
@Configuration
@Slf4j
public class ReadyQueueListener implements MessageListener {

    @Autowired
    private BaseQueueCase baseQueueCase;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String topic = new String(bytes);
        String context = new String(message.getBody()).replace("\"","");
        log.info("开始处理订阅到的内容： topic:{},context:{}", topic, context);
        // 根据不同的订阅内容执行不同逻辑
        switch (context){
             // 计算当日电费
            case "baseQueueCase":
                baseQueueCase.run(context);
                break;
            default:
                break;
        }
    }

    /**
     * 注入消息监听容器
     *
     * @param redisTemplate   获取连接工厂
     * @param listenerAdapter 监听处理器1
     * @param listenerAdapter 监听处理器2 (参数名称需和监听处理器的方法名称一致，因为@Bean注解默认注入的id就是方法名称)
     * @return
     */
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(RedisTemplate redisTemplate, ReadyQueueListener listenerAdapter) {
        RedisConnectionFactory redisConnection = redisTemplate.getConnectionFactory();
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnection);
        //订阅一个叫 redisSub 的信道
        container.addMessageListener(listenerAdapter, new ChannelTopic("redisSub"));
        //这个container 可以添加多个 messageListener
        return container;
    }
}
